<!-- 任务管理-->
<!DOCTYPE html>
<html lang="en">
<head>
    <script src="/static/js/jquery-3.4.1.min.js"></script>
    <script src="/static/layui/layui.js"></script>
    <script src="/static/layui/plugin/xm-select.js"></script>
    <link rel="stylesheet" href="/static/layui/css/layui.css">
</head>
<style>
.layui-form-label{
  white-space: nowrap;
}
</style>
<body>

<!-- 卡片搜索面板-->
<div style="padding: 20px; background-color: #F2F2F2;">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md6">
            <div class="layui-card">
                <div class="layui-card-header"><span style="margin-right: 10px; margin-bottom: 2px" class="layui-badge-dot"></span>快速搜索1</div>
                <div class="layui-card-body">
                    <div style="margin-bottom: 10px">
                        <label class="layui-form-label">任务名称</label>
                        <div class="layui-input-block" style="width: 200px">
                            <input id="search-input-name" type="text" name="title" required  lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 新建弹窗 -->
<script type="text/html" id="task-insert">
    <form class="layui-form" method="post">
        <div class="layui-form-item" style="padding-right: 50px">
            <label class="layui-form-label">任务名称</label>
            <div class="layui-input-block">
                <input id="task_name" type="text" name="name" required  lay-verify="required" placeholder="请输入任务名称, 如: 新用户任务" autocomplete="off" class="layui-input">
            </div>
        </div>
        <#--  <div class="layui-form-item" style="padding-right: 50px;">
            <label class="layui-form-label">是否新用户</label>
            <div class="layui-input-block">
                <input id="is_new" type="checkbox" lay-filter="insert_switch" lay-skin="switch" lay-text="是|否" >
            </div>
        </div>  -->
        <div class="layui-form-item" style="padding-right: 50px">
            <label class="layui-form-label">完成公交次数</label>
            <div class="layui-input-block">
                <input id="bus_count" type="text" name="bus_count"  autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item" style="padding-right: 50px">
            <label class="layui-form-label">优先级</label>
            <div class="layui-input-block">
                <input id="priority" type="text" autocomplete="off" required class="layui-input">
            </div>
        </div>

        <div class="layui-form-item" style="padding: 20px">
            <label class="layui-form-label">任务奖励</label>
            <button id="newAward" type="button" class="layui-btn layui-btn-sm " style="float: right"><i class="layui-icon"></i> 新增</button>
            <br>
            <table class="layui-table" id="award_tbl">
                <colgroup>
                    <col width="150">
                    <col width="150">
                    <col width="200">
                    <col>
                </colgroup>
                <thead>
                <tr>
                    <th>卡券</th>
                    <th>数量</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr id="row1">
                    <td>
                        <select id="award_list_1" name="interest" style="width: 100px" >

                        </select>
                    </td>
                    <td>
                        <input id="award_num_1" type="text" name="name" required  lay-verify="required" placeholder="" autocomplete="off" class="layui-input" value="1">
                    </td>
                    <td><button type="button" id="delAward" class="layui-btn layui-btn-sm " style="display: none"><i class="layui-icon"></i> 删除</button></td>
                </tr>

                </tbody>
            </table>
        </div>

        <div class="layui-form-item" style="padding-right: 50px">
            <label class="layui-form-label">选择短信模板</label>
            <div class="layui-input-block">
                <select id="selectLineStart" name="busLineInfo.lineStart" lay-filter="selectLineStart"
                        placeholder="" value="" required lay-verify="required" autocomplete="off">
                    <option></option>
                </select>
            </div>
            <label class="layui-form-label">完成任务短信</label>
            <div class="layui-input-block">
                <textarea id="finish_tips" name="finish_tips" placeholder="" class="layui-textarea"></textarea>
            </div>
        </div>

        <div class="layui-form-item layui-form-text" style="padding-right: 50px">
            <label class="layui-form-label">短信关键字</label>
            <div class="layui-input-block" id="keyWordBox">
                <#--  <input id="keyword" type="text" autocomplete="off" required class="layui-input">  -->
            </div>
        </div>

        <#--  <div class="layui-form-item" style="padding-right: 50px">
            <label class="layui-form-label">完成任务短信</label>
            <div class="layui-input-block">
                <textarea id="finish_tips" name="finish_tips" placeholder="" class="layui-textarea"></textarea>
            </div>
        </div>  -->
        <div class="layui-form-item layui-form-text" style="padding-right: 50px">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <textarea id="task_desp" name="description" placeholder="" class="layui-textarea"></textarea>
            </div>
        </div>
<#--        <div class="layui-form-item" style="padding-right: 50px">-->
<#--            <label class="layui-form-label">开始时间</label>-->
<#--            <div class="layui-input-block">-->
<#--                <input id="begin_time" type="text" name="begin_time" required   autocomplete="off" class="layui-input">-->
<#--            </div>-->
<#--        </div>-->
<#--        <div class="layui-form-item" style="padding-right: 50px">-->
<#--            <label class="layui-form-label">结束时间</label>-->
<#--            <div class="layui-input-block">-->
<#--                <input id="end_time" type="text" name="end_time" required   autocomplete="off" class="layui-input">-->
<#--            </div>-->
<#--        </div>-->
    </form>
    <div class="layui-btn-container" style="text-align: center">
        <button class="layui-btn " id="confirm" >确定</button>
    </div>
</script>

<table id="dept-table" lay-filter="dept-table"></table>


<script type="text/html" id="toolbar">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="addDept">添加</button>
    </div>
</script>

<script type="text/html" id="barTpl">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<#--  <script type="text/html" id="templetName">
    {{d.templateId = d.templateId == "25239e156f3f11ea8fb700163e120a20" ? "模板1" : d.templateId == "286658d26f3f11ea8fb700163e120a20" ? "模板2" :
                    d.templateId == "2a8f8e406f3f11ea8fb700163e120a20" ? "模板3" : "模板4"}}

</script>  -->


<script>
    //删除<tr/>
    let deltr =function(index) {
        $("tr[id='row"+index+"']").remove();//删除当前行
    };

    function loadAwardList(obj,id) {
        let html = "";
        $.each(award_list, function(i,v){
            let select = "";
            if(id != null && id == v.ticketId){
                select = "selected";
            }
            html += "<option value="+v.ticketId+" "+select+" >"+v.name+"</option>";
        });
        $(obj).append(html);
    }

    //加载短信模板下拉列表
    function loadMsgList(obj,id) {
        let html = "";
        $.each(msg_list,function(i,v){
            let select = "";
            if(id != null && id == v.id){
                select = "selected";
            }
            html += "<option value="+v.id+" "+select+" >"+"模板"+(i+1)+"</option>";
        });
        $(obj).append(html);
    }
    let templateId = "";
    let idList = [];
    layui.use(['form','layer'],function(){
        var form = layui.form;
        var layer = layui.layer;
        form.on('select(selectLineStart)',function(data){
            <#--  console.log($('#selectLineStart').prop('selectedIndex'));  -->
            $("#keyWordBox").html("");
            idList = [];
            //保存选中的模板id
            templateId = data.value;
            var index = $('#selectLineStart').prop('selectedIndex');
            $('#finish_tips').val(msg_list[index-1].content);
            var len = msg_list[index-1].keyword_num;
            if(len>0){
                for(var i=0;i<msg_list[index-1].keyword_num;i++){
                    var html = "<input id=keyword"+(i+1)+" type=text autocomplete=off required class=layui-input style=margin-bottom:10px placeholder=关键字"+(i+1)+">"
                    $('#keyWordBox').append(html);
                    idList.push("keyWord"+(i+1));
                }
            }else{
                $("#keyWordBox").html("");
                idList=[];
            }
        })
    });

    function appendLineWithData(_len,id,num){
        if(num == null){
            num = 1;
        }
        var line = "<tr id=row"+_len+">\n" +
            "                    <td> <select id=\'award_list_"+_len+"\' name=\'interest\' style=\"width: 100px\" >"+
            "                        </select></td>\n" +
            "                    <td>\n" +
            "                        <input id=\"award_num_"+_len+"\" type=\"text\" name=\"name\" required  lay-verify=\"required\" placeholder=\"\" autocomplete=\"off\" class=\"layui-input\" value="+num+">" +
            "                    </td>\n" +
            "                    <td><button onclick=\'deltr("+_len+")\' type=\"button\" class=\"layui-btn layui-btn-sm \" ><i class=\"layui-icon\"></i> 删除</button></td>\n" +
            "                </tr>";

        $("#award_tbl").append(line);
        loadAwardList($("#award_list_"+_len),id);
        layui.form.render('select');// 必须手动刷新才生效
    }

    // 解析表格数据
    function parseAwardData() {
        let rewardInfo = "";
        let award_data = [];
        let isOk = true;
        let len = $("#award_tbl tr").length-1;// 减去表头
        for(let i = 0; i < len; i++){
            let award_id =  $("#award_list_"+(i+1)).val();
            let award_num =  $("#award_num_"+(i+1)).val();

            var regu = /^\d+$/;
            if (award_num != "") {
                if (!regu.test(award_num)) {
                    return ["",false];
                }
            }

            let newData = true;
            for(let j = 0; j < award_data.length;j++){
                if(award_data[j].id == award_id){
                    award_data[j].num += parseInt(award_num);
                    newData = false;
                    break;
                }
            }
            let i_num = parseInt(award_num);
            if(newData && i_num > 0){
                award_data.push({id:award_id,num:i_num});
            }
        }

        for(let j = 0; j < award_data.length;j++){
            rewardInfo += award_data[j].id+"="+award_data[j].num+","
        }
        rewardInfo = rewardInfo.substring(0, rewardInfo.length - 1);
        return [rewardInfo,true];
    }

    // 校验 非负数
    function check1(val){
        let regu = /^\d+$/;
        if (val != "") {
            if (!regu.test(val)) {
                return false;
            }
        }
        return true;
    }


    function editTask(data,obj) {
        let table = layui.table;
        let btn = '新建111';
        let title = '添加新任务';
        if(data != null){
            btn = '保存';
            title = '编辑任务';
        }

        layer.open({
            //btn: btn,
            btn:[],
            title: title,
            content: $("#task-insert").text(),
            offset: 't',
            area: ["500px", "600px"],
            success:function(){
                loadAwardList(award_list_1);
                loadMsgList(selectLineStart);
                $("#newAward").click(function(){
                    console.log("表格增加一行 ");
                    var _len = $("#award_tbl tr").length;
                    appendLineWithData(_len);
                });

                $("#confirm").click(function(){
                    console.log("确定按钮 ");
                    onConfirmClick(data);
                });

                layui.use('form', function () {
                    var form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
                    form.render();
                });

                layui.use('laydate', function(){
                    var laydate = layui.laydate;
                    laydate.render({
                        type: 'datetime',
                        elem: '#begin_time'
                    });

                    laydate.render({
                        type: 'datetime',
                        elem: '#end_time'
                    });
                });

                $.ajax({
                    url:"/awardLists",
                    type:"get",
                    dataType:"json",
                    success:function(res){


                        // 需要回显信息
                        if(data != null){

                            $("#task_name").val(data.name);
                            $("#task_desp").val(data.description);
                            $("#is_new").prop("checked",data.isNew==1);
                            $("#priority").val(data.priority);
                            layui.form.render('checkbox');// 必须手动刷新才生效

                            $("#bus_count").val(data.busCount);
                            $("#finish_tips").val(data.finishTips);
                            $("#begin_time").val(data.beginTime);
                            $("#end_time").val(data.endTime);

                            $("#selectLineStart").val(data.templateId);
                            if(data.keyWord != null){
                                    var array = data.keyWord.split(",");
                                    for(var i=0;i<array.length;i++){
                                    var html = "<input id=keyword"+(i+1)+" type=text autocomplete=off required class=layui-input value="+array[i]+">"
                                    $('#keyWordBox').append(html);
                                }
                            }

                            // 奖励数据的加载
                            console.log(" 回显奖励数据===========");
                            if(data.rewardInfo == null){
                                console.log(" 无数据 不做处理");
                            }else
                            {
                                console.log(" 回显数据===");
                                $("tr[id='row1']").remove();//删除第一行

                                console.log(data.rewardInfo);

                                let result_str = '';
                                let info = data.rewardInfo.split(',');
                                for(let i = 0; i < info.length;i++){

                                    let line = info[i].split('=');
                                    let id = line[0];
                                    let num = line[1];

                                    console.log("表格增加一行 存放数据 "+id+" num "+num);
                                    let _len = $("#award_tbl tr").length;
                                    appendLineWithData(_len,id,num);

                                }
                            }
                        }
                    },
                    error:function(data){
                        $.messager.alert('错误',data.msg);
                    }
                });
            },
            // 确认按钮
            // yes: function () {
            //     onConfirmClick(data);
            // }

        });
    }

    function onConfirmClick(data){
        console.log(data);
        let table = layui.table;
        let name =          $("#task_name").val();
        let description =   $("#task_desp").val();
        let is_new =        $("#is_new").prop("checked");
        let bus_count =      $("#bus_count").val();
        let finish_tips     =   $("#finish_tips").val();
        let priority        =   $("#priority").val();
        let rewardInfo      = parseAwardData()[0];
        let isOk            = parseAwardData()[1];
        let keyWord = "";
        for(var i=0; i<idList.length; i++){
            var id = '#'+idList[i];
            id = id.toLowerCase();
            keyWord = keyWord + $(id).val()+","
        }
        keyWord = keyWord.substring(0,keyWord.length-1);

        // let begin_time =    $("#begin_time").val();
        // let end_time =      $("#end_time").val();
        console.log(isOk);

        if (name.length <= 0) {
            parent.layer.msg('名称不能为空');
            return;
        }

        if (priority.length <= 0) {
            parent.layer.msg('优先级不能为空');
            return;
        }

        if(!check1(bus_count)){
            parent.layer.msg('需完成公交次数格式不正确');
            return;
        }

        if(!check1(priority)){
            parent.layer.msg('优先级格式不正确');
            return;
        }

        if(!isOk){
            parent.layer.msg('奖励数量格式不正确');
            return;
        }

        if(templateId.length<0){
            parent.layer.msg('模板不能为空');
            return;
        }

        // } else {

        if(data != null){
            // 修改操作
            // 发送更新请求
            $.ajax({
                url: '/task',
                method: 'put',
                data: JSON.stringify({
                    id: data.id,
                    name: $("#task_name").val(),
                    description: $("#task_desp").val(),
                    busCount: $("#bus_count").val(),
                    priority:priority,
                    rewardInfo:rewardInfo,
                    isNew: $("#is_new").prop("checked")?1:0,
                    finishTips: $("#finish_tips").val(),
                    beginTime: $("#begin_time").val(),
                    endTime: $("#end_time").val(),
                    templateId:$("#selectLineStart").val(),
                    keyWord:keyWord
                }),
                contentType: "application/json",

                success: function (res) {
                    console.log(res);
                    if (res.code == 200) {
                        layer.msg('更改任务信息成功', {icon: 1});
                        table.reload("dept-table");

                    } else {
                        layer.msg('更改任务信息失败', {icon: 2});
                    }
                }
            });
        }
        else
        {
            // 新增操作
            // 调用新建API
            let nowDate = new Date();
            let begin_time = new Date();
            let end_time = new Date();
            let award_text = "";

            $.ajax({
                url: '/task',
                method: 'post',
                data: {
                    name: name,
                    description: description,
                    isNew:is_new,
                    busCount:bus_count,
                    finishTips:finish_tips,
                    rewardInfo:rewardInfo,
                    priority:priority,
                    // beginTime:begin_time,
                    // endTime:end_time,
                    createdTime: nowDate,
                    // rewardIds:text
                    templateId:templateId,
                    keyWord:keyWord
                },
                success: function (res) {
                    if (res.code == 200) {
                        // 执行局部刷新, 获取之前的TABLE内容, 再进行填充
                        var dataBak = [];
                        var tableBak = table.cache.dept-table;
                        for (var i = 0; i < tableBak.length; i++) {
                            dataBak.push(tableBak[i]);      //将之前的数组备份
                        }

                        dataBak.push({
                            name: $("#dept-name"),
                            description: $("#dept-description"),
                            name : $("#task_name").val(),
                            description : $("#task_desp").val(),
                            is_new : $("#is_new").prop('checked'),
                            bus_count : $("#bus_count").val(),
                            finish_tips : $("#finish_tips").val(),
                            // begin_time : $("#begin_time").val(),
                            end_time : $("#end_time").val(),
                            rewardInfo:rewardInfo,
                            createdTime: nowDate,
                            templateId:templateId,
                            keyWord:keyWord
                        });
                        //console.log(dataBak);
                        table.reload("dept-table",{
                            data:dataBak   // 将新数据重新载入表格
                        });
                        layer.msg('新建任务成功', {icon: 1});
                    } else {
                        layer.msg('新建任务失败', {icon: 2});
                    }
                }
            });
        }
    }

    // 数据地址
    const dataUrl = '/uni/dataSet';

    let award_list = [];
    let msg_list = [];

    console.log("表格初始化");
    // 表格初始化
    layui.use('table', function(){
        let table = layui.table;
        table.render({
            elem: '#dept-table',
            url: '/uni/dataSet',
            method: "post",
            request: {
                "serviceId": 101
            },
            toolbar: '#toolbar',
            parseData: function (res) {
                console.log(res);
                // award_list = res.award_list;
                // msg_list = res.msg_list;
                return {
                    "code": 0,
                    "msg": "",
                    "count": res.size,
                    data: res.data
                }
            }
            ,cols: [[
                {field:'id', width:80, title: 'ID',sort: true},
                {field:'name', width:150, title: '任务名称',sort: true},
                // {field:'isNew', width:150, title: '是否新用户',templet:function (row) {
                //         return [
                //             '<input disabled type="checkbox" lay-filter="admin_switch" lay-skin="switch" lay-text="是|否" ',
                //             row.isNew == true ? "checked />" : " />"
                //         ].join('');}},
                {field:'busCount', width:150, title: '需完成公交次数',sort: true},
                {field:'rewardInfo', width:150, title: '任务奖励信息',templet:function (row) {

                        if (row.rewardInfo != null && row.rewardInfo != ''){
                            let result_str = '';
                            let info = row.rewardInfo.split(',');
                            $.each(info, function(i,val){

                                let line = val.split('=');
                                let id = line[0];
                                let name = id;

                                for (let  j = 0;j < award_list.length;j++){
                                    if(id == award_list[j].ticketId){
                                        name = award_list[j].name;
                                        break ;
                                    }
                                }

                                let num = line[1];
                                result_str += name+"X"+num+",";
                            });
                            result_str = result_str.substring(0, result_str.length - 1);
                            return result_str;
                        }else
                        {
                            return '无';
                        }
                        return row.rewardInfo;
                        },},
                {field:'finishTips', width:150, title: '短信内容'},
                <#--  {field:'templateId', width:150, title: '模板名称',templet: '#templetName'},  -->
                {field:'keyWord', width:150, title: '关键字'},
                // {field:'beginTime', width:180, title: '任务开始时间'},
                // {field:'endTime', width:180, title: '任务结束时间'},
                {field:'priority', width:150, title: '优先级',sort: true},
                {field:'description', width:120, title:'备注'},
                {field:'createdTime', width:180, title: '创建时间'},
                {fixed: 'right', width:150, align:'center', toolbar: '#barTpl'}
            ]]
            ,page: true
            ,done: function () {

            }
        });

        table.on('toolbar(dept-table)', function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            switch(obj.event){
                case 'addDept':editTask();
            }
        });



        //监听工具条(右侧)
        table.on('tool(dept-table)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            if(layEvent === 'edit'){ //编辑
                editTask(data,obj);
            } else if (layEvent == 'del') {
                layer.confirm('确定要删除任务' + data.name + '?', {skin: 'layui-layer-molv',offset:'c', icon:'0'},function(index){
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                    //向服务端发送删除指令
                    $.ajax({
                        url: '/task/' + data.id,
                        type: 'delete',
                        success: function (res) {
                            console.log(res);
                            if (res.code == 200) {
                                layer.msg('删除任务成功', {icon: 1, skin: 'layui-layer-molv', offset:'c'});
                            } else {
                                layer.msg('删除任务失败', {icon: 2, skin: 'layui-layer-molv', offset:'c'});
                            }
                        }
                    })
                });
            }
        });

        /* 搜索实现, 使用reload, 进行重新请求 */
        $("#search-input-name").on('input',function () {
            search(table);
        });

        function search(table) {
            // 用来传递到后台的查询参数MAP
            var whereData = {};
            var qname = $("#search-input-name").val();

            if (qname.length > 0) whereData["qname"] = qname;
            table.reload("dept-table",{
                where: {
                    query: JSON.stringify(whereData)
                }
                ,page: {
                    curr: 1
                }
            });
        }
    });


</script>
</body>
</html>
